package com.young.dubbo.framework;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;

/**
 * 代理工厂，根据接口信息创建对应的代理对象，由代理对象发起对应的http请求，请求远端服务
 */
public class ProxyFactory {
    public static <T> T getProxy(final Class interfaceClass){
        return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[]{interfaceClass}, new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Invocation invocation = new Invocation(interfaceClass.getName(), method.getName(), args, method.getParameterTypes());
                Protocol protocol = ProtocolFactory.getProtocol();
                List<URL> urls = protocol.getUrls(interfaceClass.getName());
                URL url = LoadBalance.random(urls);
                String result = protocol.send(url.getHost(),url.getPort(),invocation);
                return result;
            }
        });
    }
}
